import { ref } from 'vue';
import useReplyModifier from './reply-modifier';
import { message } from 'ant-design-vue';
import 'ant-design-vue/es/message/style/css';

export default function useReplyModal(replyList, replyUrl) {
  const isReplyModalShow = ref(false);
  const currentReplyTarget = ref(null);

  const { postReply } = useReplyModifier(replyList, replyUrl);

  // reply modal才知道哪个post（也就是target）触发了评论，所以，对于target的`replyCount++`是reply modal的职能
  // 对于有的reply是二级reply，也就是回复其它评论的reply，对于被回复的评论的`replyCount++`，由`replyModifier`提供
  const openReplyModal = (target) => {
    currentReplyTarget.value = target;
    isReplyModalShow.value = true;
  };

  const handlePostReply = (parentReplyId, content) => {
    if (currentReplyTarget == null) return;
    const replyObj = {
        targetId: currentReplyTarget.value.id,
        content,
        parentCommentId: parentReplyId
    };
    postReply(
      replyObj,
      () => { 
        message.success("评论成功");
        currentReplyTarget.value.replyCount++;
      },
      (e) => {
        if (e) message.error(`评论失败: ${e}`);
        else message.error(`评论失败，未知错误`);
      },
      () => { isReplyModalShow.value = false; currentReplyTarget.value = null;})
  };

  return { openReplyModal, isReplyModalShow, handlePostReply };
}